package com.uuuo.rxcache;

import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.uuuo.rxcache.entities.BeautyPhotoInfo;
import com.uuuo.rxcache.net.Repository;

import java.io.File;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity {
    Repository repository;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    public void init(View view) {
        File file = new File(Environment.getExternalStorageDirectory() + "/1RxCache");
        if (!file.exists()) {
            file.mkdirs();
        }
        repository = Repository.init(file);
    }

    int offset = 0;
    boolean isUpdate = true;

    public void reset(View view) {
        offset = 0;
        isUpdate = !isUpdate;
        Log.w("*********", "isUpdate:" + isUpdate);
    }


    public void getBeauty(View view) {
        String user = ((EditText) findViewById(R.id.edtName)).getText().toString();
        repository.getBeautyPhoto(offset += 5, user, isUpdate)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .flatMap(new Func1<Map<String, List<BeautyPhotoInfo>>, Observable<List<BeautyPhotoInfo>>>() {
                    @Override
                    public Observable<List<BeautyPhotoInfo>> call(Map<String, List<BeautyPhotoInfo>> newsListMap) {
                        return Observable.just(newsListMap.get("美女"));
                    }
                })
                .subscribe(new Observer<List<BeautyPhotoInfo>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(List<BeautyPhotoInfo> beautyPhotoInfos) {
                        for (BeautyPhotoInfo be : beautyPhotoInfos) {
                            Log.w("*********", be.getTitle());
                        }
                    }
                });
    }

}
